package com.xcity.db.entity;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import com.xcity.util.DBUtils;

import naga.x.db.IMapper;

public abstract class AbstractEntity<M extends IMapper<? extends AbstractEntity<?>>> implements Serializable {

	protected EntityState state;
	protected Class<M> mapperType;
	
	public AbstractEntity() {
		state = EntityState.UPDATE;
		ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
		mapperType = (Class<M>) type.getActualTypeArguments()[0];
	}

	public EntityState getState() {
		return state;
	}

	public void setState(EntityState state) {
		EntityState oldState = this.state;
		if (oldState == null) {
			this.state = state;
			return;
		}
		switch (oldState) {
			case INSERT:
				if (state == EntityState.DELETE || state == EntityState.NONE) {
					this.state = EntityState.NONE;
				}
				break;
			case UPDATE:
				if (state == EntityState.DELETE) {
					this.state = state;
				}
				break;
			case DELETE:
				if (state == EntityState.UPDATE) {
					this.state = state;
				}
				break;
			case NONE:
				if (state == EntityState.INSERT) {
					this.state = state;
				}
				break;
		}
	}
	
	public void save() {
		switch (state) {
			case INSERT:
				state = EntityState.UPDATE;
				DBUtils.insert(mapperType.getName() + ".save", this);
				break;
			case DELETE:
				DBUtils.delete(mapperType.getName() + ".delete", this);
				break;
			case UPDATE:
				DBUtils.update(mapperType.getName() + ".update", this);
				break;
		}
	}
	
}
